package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.NewActionHelp;
import com.ciko.code.bean.UserBean;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000204.R;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.util.Util;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import logic.bean.AdvertisementInfo;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;


public class AdvertisementActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener {
    private Timer mTimer;

    private ImageView advertisementImg;

    private String downloadPath;
    private String oldPath;
    private String oldImgUrl;
    private String linkUrl;
    private String title;
    private int showTime;
    private int length;

    private AdvertisementInfo adinfo = new AdvertisementInfo();
    private UserDao userDao;
    private UserBean user;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.advertisement);
        context = this;
        downloadPath = "data/data/" + context.getPackageName() + "/";
        oldPath = QyreaderPerferencesUtil.getInstance(context, "0").getAdvertisementDownloadPath();
        oldImgUrl = QyreaderPerferencesUtil.getInstance(context, "0").getAdvertisementImageUrl();
        length = QyreaderPerferencesUtil.getInstance(context, "0").getAdvertisementImageLength();
        linkUrl = QyreaderPerferencesUtil.getInstance(context, "0").getAdvertisementLinkUrl();
        title = QyreaderPerferencesUtil.getInstance(context, "0").getAdvertisementTitle();
        showTime = QyreaderPerferencesUtil.getInstance(context, "0").getAdvertisementShowTime();
        initData();
        initView();
        setListener();
    }

    private boolean downloadFinished() {
        if (new File(oldPath).length() < length) {
            return false;
        }
        return true;
    }

    @Override
    public void onDestroy() {
        finish();
        super.onDestroy();
    }

    private void setListener() {
        advertisementImg.setOnClickListener(this);
    }

    private void initView() {
        advertisementImg = (ImageView) findViewById(R.id.advertisement);
        if (Util.isNotEmpty(oldPath) && downloadFinished()) {
            Bitmap bitmap = BitmapFactory.decodeFile(oldPath);
            advertisementImg.setImageDrawable(new BitmapDrawable(bitmap));
            mTimer = new Timer();
            setTimerTask();
        } else {
            user = userDao.getLastLoginUser();
            if (null != user && user.getIsKeepPwd() == 1) {
                onDestroy();
            } else {
                goLoginActivity();
            }
        }
    }

    private void setTimerTask() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                doActionHandler.sendMessage(message);
            }
        }, showTime * 1000);
    }

    private void downloadAdvertisementImg(final String url) {
        new Thread() {
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementImageKLength(conn.getContentLength());
                    InputStream is = conn.getInputStream();
                    FileOutputStream fos = new FileOutputStream(downloadPath);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    is.close();
                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }

    private Handler doActionHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int msgId = msg.what;
            switch (msgId) {
                case 1:
                    user = userDao.getLastLoginUser();
                    if (null != user && user.getIsKeepPwd() == 1) {
                        onDestroy();
                    } else {
                        goLoginActivity();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void initData() {
        userDao = UserDao.getInstance(context);
        NewActionHelp.qryEnterpriseAdvertiseMentStartPage(context, new getAdvertisementPageHandler());
    }

    private class getAdvertisementPageHandler
            extends
            ObjectHttpResponseHandler<AdvertisementInfo> {

        @Override
        public Type getType() {
            return new TypeToken<AdvertisementInfo>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {

        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, AdvertisementInfo arg2, String arg3) {
            System.err.println(arg3);
            if (arg2 == null) {
                if (!downloadFinished()) {
                    downloadPath = oldPath;
                    downloadAdvertisementImg(oldImgUrl);
                } else {
                    QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementDownloadPath("");
                }
                return;
            }
            adinfo = arg2;
            String imgName = adinfo.getImgUrl().substring(adinfo.getImgUrl().lastIndexOf("/") + 1, adinfo.getImgUrl().length());
            downloadPath = downloadPath + imgName;
            if (!downloadPath.equals(oldPath) || (downloadPath.equals(oldPath) && !downloadFinished())) {
                QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementDownloadPath(downloadPath);
                QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementImageUrl(adinfo.getImgUrl());
                QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementLinkUrl(adinfo.getLinkUrl());
                QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementTitle(adinfo.getTitle());
                QyreaderPerferencesUtil.getInstance(context, "0").setAdvertisementShowTime(adinfo.getShowTime());
                downloadAdvertisementImg(adinfo.getImgUrl());
            }
        }

    }

    void goLoginActivity() {
        Intent intent = new Intent();
        intent.setClass(this, NewLoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.advertisement:
                if (Util.isNotEmpty(linkUrl)) {
                    Intent webIntent = new Intent(this, CommonWebActivity.class);
                    webIntent.putExtra(DefaultConsts.req_url_s, linkUrl);
                    webIntent.putExtra(DefaultConsts.title_s, title);
                    webIntent.putExtra("mark", 1);
                    startActivity(webIntent);
                    this.finish();
                }
                break;
            default:
                break;
        }

    }

    @Override
    public Handler getUIHandler() {
        return null;
    }

}
